package hlhj.fhp.burst.activitys

import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.annotation.GlideOption
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.squareup.picasso.Picasso
import com.tbruyelle.rxpermissions.RxPermissions
import com.tenma.ventures.base.TMActivity
import com.tenma.ventures.bean.utils.TMEnterUtil
import com.tenma.ventures.bean.utils.TMLocationUtils
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.plugins.location.TMLocation
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import hlhj.fhp.burst.Contents
import hlhj.fhp.burst.FileUtil
import hlhj.fhp.burst.R
import hlhj.fhp.burst.bean.*
import hlhj.fhp.burst.camera.util.LogUtil
import hlhj.fhp.burst.customView.ChooseDialog
import hlhj.fhp.burst.customView.LoadingDialog
import hlhj.fhp.burst.customView.NewGlideEngin
import kotlinx.android.synthetic.main.activity_camera_aty.*
import kotlinx.android.synthetic.main.activity_to_burst_aty.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.ArrayList

class ToBurstAty : TMActivity(), ChooseDialog.OnChooseCommitListener {
    private val PICK_IMG=1
    private val PICK_VIDEO=2
    private var type=0 //1图片 2 视频
    private val pics=ArrayList<String>()
    private val picFiles=ArrayList<File>()
    private lateinit var imgThumbFile:File
    private lateinit var videoFile:File
    private var imgthumbUrl=""
    private val CAMERA_RESULT=11
    private lateinit var  adp :BaseQuickAdapter<String,BaseViewHolder>
    private var qnUrl=""
    private var qnToekn=""
    private var cdn=""
    private var qnkey=""
    private var isok=true
    private var address=""
    private val picUrls=ArrayList<String>()
    private lateinit var loadingDialog:LoadingDialog
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_to_burst_aty)
        if (null!=TMSharedPUtil.getTMThemeColor(this)&&TMSharedPUtil.getTMThemeColor(this).length>0){
            loTittle.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this)))
        }
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        EventBus.getDefault().register(this)
        initView()
        pics.add("jiahao")
        loadingDialog= LoadingDialog(this)
        loadingDialog.setCancelable(false)
        getQnToken()

        recyclerview.adapter=adp
        recyclerview.layoutManager=GridLayoutManager(this,3)

        if (!RxPermissions.getInstance(this).isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                || RxPermissions.getInstance(this).isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)){
            RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe {
                        boo->
                        if (boo){
                            getCity()

                        }
                    }
        }
        initListener()
    }

    private fun getCity() {
        Thread(Runnable {
            val location = TMLocationUtils.getLocation(this)
            address="${location.addressComponent.city} .${location.addressComponent.district}.${location.addressComponent.street}"
        }).start()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun initView() {
        if (!TextUtils.isEmpty(TMSharedPUtil.getTMThemeColor(this@ToBurstAty))){
            val drawable = btCommit.background as GradientDrawable
            drawable.setColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(this@ToBurstAty)))
        }
        btExit.setOnClickListener {
            finish()
        }
        adp=object :BaseQuickAdapter<String,BaseViewHolder>(R.layout.pub_item,pics){
            override fun convert(helper: BaseViewHolder?, item: String?) {
                val img = helper?.getView<ImageView>(R.id.itemImg)!!
                val btGo = helper?.getView<View>(R.id.btGo)
                if (item?.equals("jiahao")!!){
                    btGo.visibility=View.VISIBLE
                    img.visibility=View.GONE
                    val options = RequestOptions().centerInside()
                    Glide.with(mContext).load(R.drawable.ic_bl_zhaopian).apply(options).into(img)
                    helper?.setVisible(R.id.btDelet,false)
                    btGo.setOnClickListener {
                        ChooseDialog(mContext,this@ToBurstAty).show()
                    }
                }else{
                    btGo.visibility=View.GONE
                    img.visibility=View.VISIBLE

                    val options = RequestOptions().centerCrop()

                    Glide.with(mContext).load(item).apply(options).into(img)
                    helper?.setVisible(R.id.btDelet,true)
                }
                val params = img.layoutParams as RelativeLayout.LayoutParams
                if (type==2){
                    if (helper?.adapterPosition==0){
                        helper?.setVisible(R.id.ig_play,true)
                    }else{
                        helper?.setVisible(R.id.ig_play,false)
                    }
                }else{
                    helper?.setVisible(R.id.ig_play,false)
                }
                /*Thread(Runnable {
                    Thread.sleep(1)
                    Log.e("info",img.measuredWidth.toString())
                    params.height=img.measuredWidth
                    when(helper?.adapterPosition%3){
                        0->{
                            params.setMargins(0,0,10,0)
                        }
                        1->{
                            params.setMargins(0,0,10,0)
                        }
                        2->{
                            params.setMargins(0,0,0,0)
                        }
                    }
                    runOnUiThread {
                        img.layoutParams=params
                    }
                }).start()*/
                /*删除*/
                val btDelet = helper?.getView<ImageView>(R.id.btDelet)
                btDelet.setOnClickListener {
                    if (type==1){
                        pics.removeAt(helper?.adapterPosition)
                        if (pics.size==1){
                            type=0
                        }
                        picFiles.removeAt(helper?.adapterPosition)
                        notifyItemRemoved(helper?.adapterPosition)
                    }else if (type==2){
                        pics.removeAt(helper?.adapterPosition)
                        type=0
                        notifyItemRemoved(helper?.adapterPosition)
                    }

                }
            }
        }
    }

    private fun getQnToken() {
        OkGo.get<String>(Contents.PUBLICK_URL+Contents.QNVIDEO)
                .params("token",TMSharedPUtil.getTMToken(this@ToBurstAty))
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val str = response?.body()
                        val qnBean = Gson().fromJson(str, QnBean::class.java)
                        if (qnBean.code==1){
                            qnToekn=qnBean.data.token
                            qnUrl=qnBean.data.url
                            cdn=qnBean.data.cdn
                        }
                    }
                })
    }

    private fun initListener() {

        etContent.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                val str = s.toString()
                tvNum.text="${str.length}/300字"
                isok = str.length <= 300

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        btCommit.setOnClickListener {
            btCommit.isClickable=false
            if (TextUtils.isEmpty(TMSharedPUtil.getTMUser(this).mobile)){
                TMEnterUtil.gotoBindingmobile(this,"","","")
                btCommit.isClickable=true
                return@setOnClickListener
            }
            if (!isok){
                Toast.makeText(this@ToBurstAty,"字数超过限制",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }else{
                loadingDialog.show()
                when(type){
                    0->{//文字
                        if (picFiles.size==0){
                            OkGo.get<String>(Contents.PUBLICK_URL+Contents.PUB_STORY)
                                    .params("token",TMSharedPUtil.getTMToken(this@ToBurstAty))
                                    .params("content",etContent.text.toString())
                                    .params("address",address)
                                    .params("source_type",0)
                                    .execute(object :StringCallback(){
                                        override fun onSuccess(response: Response<String>?) {
                                            loadingDialog.dismiss()
                                            btCommit?.isClickable=true
                                            val body = response?.body()
                                            val bean = Gson().fromJson(body, BaseBean::class.java)
                                            if (bean.code==1){
                                                Toast.makeText(this@ToBurstAty,"爆料成功",Toast.LENGTH_SHORT).show()
                                                finish()
                                            }else{
                                                Toast.makeText(this@ToBurstAty,"错误！",Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    })
                        }
                    }
                    1->{//图文
                        val request = OkGo.post<String>(Contents.PUBLICK_URL + Contents.UPLOAD)
                        for (i in 0..picFiles.size-1){
                            request.params("file${i}",picFiles[i])
                        }
                        LogUtil.e("info",picFiles.toString()+"-"+picFiles.size)
                        request.execute(object :StringCallback(){
                            override fun onSuccess(response: Response<String>?) {
                                val str = response?.body()
                                val uploadBean = Gson().fromJson(str, UploadBean::class.java)
                                if (uploadBean.code==1){
                                    var pic=""
                                    for (j in 0..uploadBean.data.size-1){
//                                    picUrls.add(uploadBean.data[j].save_path)
                                        if (j==0){
                                            pic=pic+uploadBean.data[j].save_path
                                        }else{
                                            pic=pic+","+uploadBean.data[j].save_path
                                        }
                                    }
                                    OkGo.get<String>(Contents.PUBLICK_URL+Contents.PUB_STORY)
                                            .params("token",TMSharedPUtil.getTMToken(this@ToBurstAty))
                                            .params("content",etContent.text.toString())
                                            .params("source_type",1)
                                            .params("source",pic)
                                            .params("address",address)

                                            .execute(object :StringCallback(){
                                                override fun onSuccess(response: Response<String>?) {
                                                    loadingDialog.dismiss()
                                                    btCommit?.isClickable=true
                                                    val body = response?.body()
                                                    val bean = Gson().fromJson(body, BaseBean::class.java)
                                                    if (bean.code==1){
                                                        Toast.makeText(this@ToBurstAty,"爆料成功",Toast.LENGTH_SHORT).show()
                                                        finish()
                                                    }else{
                                                        Toast.makeText(this@ToBurstAty,"错误！",Toast.LENGTH_SHORT).show()
                                                    }
                                                }
                                            })
                                }else{
                                    Toast.makeText(this@ToBurstAty,"上传失败",Toast.LENGTH_LONG).show()
                                    btCommit.isClickable=true
                                }
                            }

                        })
                    }
                    2->{//视频
                        OkGo.post<String>(qnUrl)
                                .params("token",qnToekn)
                                .params("file",videoFile)
                                .execute(object :StringCallback(){
                                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                        super.onStart(request)
                                        loadingDialog.show()
                                    }
                                    override fun onSuccess(response: Response<String>?) {
                                        val body = response?.body()
                                        val hashBean = Gson().fromJson(body, HashBean::class.java)
                                        if (hashBean!=null){
                                            qnkey=hashBean.key
                                            OkGo.post<String>(Contents.PUBLICK_URL+Contents.UPLOAD)
                                                    .params("file",imgThumbFile)
                                                    .execute(object :StringCallback(){
                                                        override fun onSuccess(response: Response<String>?) {
                                                            val s = response?.body()
                                                            val baseBean = Gson().fromJson(s, UploadBean::class.java)
                                                            if(baseBean.code==1){
                                                                imgthumbUrl=baseBean.data[0].save_path


                                                                /*开始发布*/

                                                                OkGo.get<String>(Contents.PUBLICK_URL+Contents.PUB_STORY)
                                                                        .params("token",TMSharedPUtil.getTMToken(this@ToBurstAty))
                                                                        .params("content",etContent.text.toString())
                                                                        .params("source_type",2)
//                                                                        .params("source",cdn+"/"+qnkey)
                                                                        .params("source",qnkey)
                                                                        .params("address",address)
                                                                        .params("video_thumb",imgthumbUrl)

                                                                        .execute(object :StringCallback(){
                                                                            override fun onSuccess(response: Response<String>?) {
                                                                                btCommit?.isClickable=true
                                                                                loadingDialog.dismiss()
                                                                                val str = response?.body()
                                                                                val bean = Gson().fromJson(str, BaseBean::class.java)
                                                                                if (bean?.code==1){
                                                                                    Toast.makeText(this@ToBurstAty,"发布成功",Toast.LENGTH_SHORT).show()
                                                                                    finish()
                                                                                }else{
                                                                                    Toast.makeText(this@ToBurstAty,"发布失败",Toast.LENGTH_SHORT).show()
                                                                                    finish()
                                                                                }
                                                                            }
                                                                        })
                                                            }
                                                        }
                                                    })
                                        }
                                    }

                                    override fun onError(response: Response<String>?) {
                                        super.onError(response)
                                        loadingDialog.dismiss()
                                        btCommit.isClickable=true
                                    }
                                })
                    }
                }
            }
        }

    }

    /*选择照片*/
    override fun shoot() {
        val intent = Intent(this@ToBurstAty, CameraAty::class.java)
        startActivityForResult(intent,CAMERA_RESULT)

    }

    override fun img() {
        Matisse.from(this@ToBurstAty)
                .choose(MimeType.ofImage())
                .maxSelectable(9)
                .showSingleMediaType(true)
                .countable(true)
                .thumbnailScale(0.85f)
                .theme(R.style.Matisse_Zhihu)
                .imageEngine(NewGlideEngin())
                .forResult(PICK_IMG)

    }

    override fun video() {

        Matisse.from(this@ToBurstAty)
                .choose(MimeType.ofVideo())
                .maxSelectable(1)
                .showSingleMediaType(true)
                .countable(true)
                .thumbnailScale(0.85f)
                .theme(R.style.Matisse_Zhihu)
                .imageEngine(NewGlideEngin())
                .forResult(PICK_VIDEO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=-1)return
        when(requestCode){
            PICK_IMG->{
                if (type==2){
                    Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
                }else{
                    type=1
                    val list = Matisse.obtainPathResult(data)
                    for (i in 0..list.size-1){
                        if (pics.size<10){
                            pics.add(0,list[i])
                            picFiles.add(0,File(list[i]))
                        }else if (pics.size==10){
                            Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()

//                            pics.removeAt(pics.size-1)
                        }
                        else{
                            Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()
                        }
                    }
                    adp.notifyDataSetChanged()
                }

            }
            PICK_VIDEO->{
                if (type==1){
                    Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
                }else{
                    type=2
                    if (pics.size>=2){
                        Toast.makeText(this@ToBurstAty,"最多只能上传一个视频",Toast.LENGTH_LONG).show()
                    }else{
                        val list = Matisse.obtainPathResult(data)
                        val path = list[0]
                        videoFile = File(path)
                        val retriever = MediaMetadataRetriever()
                        retriever.setDataSource(path)
                        val bitmap = retriever.frameAtTime
                        imgThumbFile = FileUtil.createImageFile(bitmap, this@ToBurstAty)
                        pics.add(0,imgThumbFile.path)
                        adp.notifyDataSetChanged()
                    }

                }

            }
            CAMERA_RESULT->{
                    val bean = data!!.getSerializableExtra("bean") as TempBean
                    val cameraType = bean?.type
                    if (cameraType==110){
                        if (type==1){
                            Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
                        }else{
                            type=2
                            if (pics.size>2){
                                Toast.makeText(this@ToBurstAty,"最多只能上传一个视频",Toast.LENGTH_LONG).show()
                            }else{
                                val thumbmap =bean.bitmap
                                val path = bean.path
                                videoFile= File(path)
                                imgThumbFile=FileUtil.createImageFile(thumbmap,this@ToBurstAty)
                                pics.add(0,imgThumbFile.path)
                                adp.notifyDataSetChanged()
                            }

                        }
                    }else if (cameraType==120){
                        if (type==2){
                            Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
                        }else{
                            val thumbmap = data.getParcelableExtra<Bitmap>("bitmap")
                            val file = FileUtil.createImageFile(thumbmap,this@ToBurstAty)
                            if (pics.size<10){
                                pics.add(0,file.path)
                                picFiles.add(0,file)
                            }else if (pics.size==9){
                                Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()
                            }
                            else{
                                Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()
                            }
                            adp.notifyDataSetChanged()
                        }
                    }

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handCamera(bean: TempBean){
        val cameraType = bean.type
        if (cameraType==110){
            if (type==1){
                Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
            }else{
                type=2
                if (pics.size>=2){
                    Toast.makeText(this@ToBurstAty,"最多只能上传一个视频",Toast.LENGTH_LONG).show()
                }else{
                    val thumbmap =bean.bitmap
                    val path = bean.path
                    videoFile= File(path)
                    imgThumbFile=FileUtil.createImageFile(thumbmap,this@ToBurstAty)
                    pics.add(0,imgThumbFile.path)
                    adp.notifyDataSetChanged()
                }
            }
        }else if (cameraType==120){
            if (type==2){
                Toast.makeText(this@ToBurstAty,"只能选择图片或视频",Toast.LENGTH_LONG).show()
            }else{
                type=1
                val thumbmap = bean.bitmap
                val file = FileUtil.createImageFile(thumbmap,this@ToBurstAty)
                if (pics.size<10){
                    pics.add(0,file.path)
                    picFiles.add(0,file)
                }else if (pics.size==9){
                    Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()
                }
                else{
                    Toast.makeText(this@ToBurstAty,"最多上传9张图片",Toast.LENGTH_LONG).show()
                }
                adp.notifyDataSetChanged()
            }
        }
    }
}
